import { Request } from 'express'
import multer from 'multer'
import path from 'path'
import { config } from '../config'
import { AppError } from './errorHandler'

interface MulterCallback {
  (error: Error | null, destination?: string): void
}

interface FileNameCallback {
  (error: Error | null, filename?: string): void
}

const storage = multer.diskStorage({
  destination: (req: Request, file: Express.Multer.File, cb: MulterCallback) => {
    cb(null, config.upload.path)
  },
  filename: (req: Request, file: Express.Multer.File, cb: FileNameCallback) => {
    const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1e9)}`
    cb(null, `${file.fieldname}-${uniqueSuffix}${path.extname(file.originalname)}`)
  },
})

const fileFilter = (req: Request, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
  const allowedMimes = ['image/jpeg', 'image/png', 'image/gif']

  if (allowedMimes.includes(file.mimetype)) {
    cb(null, true)
  } else {
    cb(new AppError('Invalid file type', 400))
  }
}

export const upload = multer({
  storage,
  fileFilter,
  limits: {
    fileSize: config.upload.maxSize,
  },
})
